import AesUtil from "./AesUtil"
import config from './config'

const baseUrl = config.baseUrl
let request = 0
uni.addInterceptor('request', {
	invoke: config => {
		request++
		console.log('config', config);
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		const data = {
			data: AesUtil.encrypt(JSON.stringify(config.data))
		}
		config.header = {
			'Content-Type': 'application/json;charset=utf8;'
		}
		// if (!config.url.includes('login')) {
			const token = uni.$store.get('token')
			if (token) {
				config.header.token = token
			}
			console.log('token: ',token);
		// }
		config.data = data
		return config
	},
	complete: (res) => {
		console.log('response: ', res);
		if(res.header && res.header.token) {
			uni.$store.set('token', res.header.token, true)
		}
		request--
		if(request <= 0) {
			uni.hideLoading()
			request = 0
		}
	}
})

export default {
	/**
	 * @param url 请求地址
	 * @param data 请求参数
	 * @param header 请求头配置
	 */
	post: (url, data, header = {}) => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url,
				data: {
					...data
				},
				header: header,
				method: 'POST',
				success: ({
					data,
					statusCode
				}) => {
					console.log(111, statusCode);
					if (statusCode === 200) {
						const {
							code,
							msg
						} = JSON.parse(AesUtil.decrypt(data))
						if (msg && code !== 200) {
							uni.toast.show(msg)
						}
						resolve(JSON.parse(AesUtil.decrypt(data)))
					} else if (statusCode === 401 || statusCode === 403) {
						uni.toast.show({
							title: '请先登陆'
						})
						setTimeout(() => {
							uni.toast.hide()
							uni.reLaunch({
								url: '/pages/login/index'
							})
						}, 400)
					} else if (statusCode === 500) {
						uni.toast.show('服务器错误~')
					} else {
						uni.toast.show('网络出错啦~')
					}
				},
				fail: (error) => {
					uni.toast.show('请求失败~')
					reject(error)
				}
			})
		})
	},
	/**
	 * @param { File } file 文件
	 * @param { string } type 类型
	 */
	uploadFile: (file, type, side) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseUrl + '/upload',
				// #ifdef APP
				files: [],
				// #endif
				name: 'file',
				filePath: file.path,
				formData: {
					type,
					file,
					side
				},
				success: (res) => {
					console.log('upload:success', res);
					resolve(res)
				},
				fail: (err) => {
					console.log('upload:error', err);
					reject(err)
				}
			})
		})
	}
}